/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package heartsclient;

import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.smartcardio.Card;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import sun.awt.windows.ThemeReader;

/**
 *
 * @author quangduc
 */
public class CuaSoGame extends javax.swing.JFrame {

    Client threadMain;
    ArrayList<QuanBai> dsCardTop;
    ArrayList<QuanBai> dsCardLeft;
    ArrayList<QuanBai> dsCardRight;
    ArrayList<QuanBai> dsCardPlayer;
    ArrayList<QuanBai> dsBaiDanh;//ds bài đánh ra 
    ArrayList<QuanBai> dsBaiDoi;
    String[] baiDuocChia = new String[13];
    QuanBai baiDanhRa;
    int khoangcach = 25;
    int PlayerID = 0;
    boolean doiBai = true;
    boolean luotDi = false;
    String nameLeft = "Player";
    String nameTop = "Player";
    String nameRight = "Player";
    String namePlayer = "You";
    JLabel lblTop;
    JLabel lblLeft;
    JLabel lblRight;
    JLabel lblPlayer;
    JLabel lblThongBao;
    JButton btnDoi;

    /**
     * Creates new form CuaSoGame
     */
    public CuaSoGame(Client threadMain) {
        this.threadMain = threadMain;
        initComponents();
        //this.setSize(700, 700);   
        this.setLocationRelativeTo(null);
        //Khoi tao ds
        dsBaiDanh = new ArrayList<>();
        dsCardLeft = new ArrayList<>();
        dsCardTop = new ArrayList<>();
        dsCardRight = new ArrayList<>();
        dsCardPlayer = new ArrayList<>();
        addButton_Label();
        btnDoi.setVisible(false);
//        for (int i = 0; i < 13; i++) {
//            QuanBai card = new QuanBai(1, 0);
//            dsCardPlayer.add(card);
//        }
//        showcard();


        lblThongBao.setText("Cho du nguoi");


    }

    public void showBaiDanh() {
    }

    public void toiLuotDi() {
        luotDi = true;
        lblThongBao.setText("Toi phien ban.");
    }

    public void hetLuotDi() {
        luotDi = false;
        lblThongBao.setText("......");
    }

    public void removeCardLeft() {
        QuanBai card = dsCardLeft.get(dsCardLeft.size()-1);
        pnl.remove(card);
        dsCardLeft.remove(card);
        int y = (pnl.getHeight() / 2) - (71 + khoangcach * dsCardLeft.size()) / 2;
        for (QuanBai c : dsCardLeft) {
            c.setLocation(25, y);
            y = y + khoangcach;
        }
        for (QuanBai c : dsCardLeft) {
            pnl.add(c,0);
        }
    }

    public void removeCardTop() {
        QuanBai card = dsCardTop.get(dsCardTop.size()-1);
        pnl.remove(card);
        dsCardTop.remove(card);
        int x = (pnl.getWidth() / 2) - (69 + 25 * (dsCardTop.size() - 1)) / 2;
        for (QuanBai c : dsCardTop) {
            c.setLocation(x, 25);
            x = x + khoangcach;
        }
        for (QuanBai c : dsCardTop) {
            pnl.add(c);
        }
    }

    public void removeCardRight() {
        QuanBai card = dsCardRight.get(dsCardRight.size()-1);
        pnl.remove(card);
        dsCardRight.remove(card);
        int y = (pnl.getHeight() / 2) - (71 + khoangcach * (dsCardRight.size())) / 2;
        for (QuanBai c : dsCardRight) {
            c.setLocation(pnl.getWidth() - 71 - 25, y);
            y = y + khoangcach;
        }
        for (QuanBai c : dsCardRight) {
            pnl.add(c);
        }
    }

    public void showQuanBaiTop() {
        dsCardTop = new ArrayList<>();
        for (int i = 0; i < 13; i++) {
            QuanBai quanbai = new QuanBai(-2, 0);
            dsCardTop.add(quanbai);
        }
        //Chieu ngang tam hinh la 69
        int x = (pnl.getWidth() / 2) - (69 + 25 * (dsCardTop.size() - 1)) / 2;
        for (QuanBai c : dsCardTop) {
            c.setLocation(x, 25);
            x = x + khoangcach;
        }
        for (QuanBai c : dsCardTop) {
            pnl.add(c);
        }
    }

    public void showQuanBaiLeft() {
        dsCardLeft = new ArrayList<>();
        //Tạo bài đại diện
        for (int i = 0; i < 13; i++) {
            QuanBai card = new QuanBai(-2, 0);
            dsCardLeft.add(card);
        }
        //Chieu ngang tam hinh la 69
        int y = (pnl.getHeight() / 2) - (71 + khoangcach * dsCardLeft.size()) / 2;
        for (QuanBai c : dsCardLeft) {
            c.setLocation(25, y);
            y = y + khoangcach;
        }
        for (QuanBai c : dsCardLeft) {
            pnl.add(c);
        }
        lblLeft.setLocation(61 - lblLeft.getWidth() / 2, y + 71);
    }

    public void showQuanBaiRight() {
        dsCardRight = new ArrayList<>();
        for (int i = 0; i < 13; i++) {
            QuanBai card = new QuanBai(-2, 0);
            dsCardRight.add(card);
        }
        //Chieu ngang tam hinh la 69
        int y = (pnl.getHeight() / 2) - (71 + khoangcach * (dsCardRight.size())) / 2;
        for (QuanBai c : dsCardRight) {
            c.setLocation(pnl.getWidth() - 71 - 25, y);
            y = y + khoangcach;
        }
        for (QuanBai c : dsCardRight) {
            pnl.add(c);
        }
        lblRight.setLocation((pnl.getWidth()) - 61 - lblRight.getWidth() / 2, y + 71);
    }

    //Hiển thị bài sau khi đổi
    public void showBaiSauDoi() {
        lblThongBao.setText("Cho toi luot");
        for (int i = 1; i <= 3; i++) {
            QuanBai card = dsCardPlayer.get(dsCardPlayer.size() - i);
            card.addMouseListener(new MouseListener() {
                @Override
                public void mouseClicked(MouseEvent e) {
                }

                @Override
                public void mousePressed(MouseEvent e) {
                    chonBaimousePressed(e);
                    //throw new UnsupportedOperationException("Not supported yet.");
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    //throw new UnsupportedOperationException("Not supported yet.");
                }

                @Override
                public void mouseEntered(MouseEvent e) {
                    //throw new UnsupportedOperationException("Not supported yet.");
                }

                @Override
                public void mouseExited(MouseEvent e) {
                    //throw new UnsupportedOperationException("Not supported yet.");
                }
            });
        }
        sapXepBai();
        int x = (pnl.getWidth() / 2) - (69 + khoangcach * (dsCardPlayer.size() - 1)) / 2;
        int y = pnl.getHeight() - 71 - 50;
        for (QuanBai c : dsCardPlayer) {
            c.setLocation(x, y);
            x = x + khoangcach;
        }
        for (QuanBai c : dsCardPlayer) {
            pnl.add(c, 0);
        }
        pnl.updateUI();
    }

    public void showQuanBaiPlayer() {
        lblPlayer = new JLabel(namePlayer, JLabel.CENTER);
        lblPlayer.setSize(200, 21);
        lblPlayer.setLocation(pnl.getWidth() / 2 - lblPlayer.getWidth() / 2, pnl.getHeight() - 25);
        pnl.add(lblPlayer);
        //săp tăng dần
        sapXepBai();
        //tạo ds quân bài
        for (QuanBai card : dsCardPlayer) {
            card.addMouseListener(new MouseListener() {
                @Override
                public void mouseClicked(MouseEvent e) {
                }

                @Override
                public void mousePressed(MouseEvent e) {
                    chonBaimousePressed(e);
                    //throw new UnsupportedOperationException("Not supported yet.");
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    //throw new UnsupportedOperationException("Not supported yet.");
                }

                @Override
                public void mouseEntered(MouseEvent e) {
                    //throw new UnsupportedOperationException("Not supported yet.");
                }

                @Override
                public void mouseExited(MouseEvent e) {
                    //throw new UnsupportedOperationException("Not supported yet.");
                }
            });
        }
        //Chieu ngang tam hinh la 69
        int x = (pnl.getWidth() / 2) - (69 + khoangcach * (dsCardPlayer.size() - 1)) / 2;
        int y = pnl.getHeight() - 71 - 50;
        for (QuanBai c : dsCardPlayer) {
            c.setLocation(x, y);
            x = x + khoangcach;
        }
        for (QuanBai c : dsCardPlayer) {
            pnl.add(c, 0);
        }
        pnl.updateUI();
    }

    public void sapXepBai() {
        for (int i = 0; i < dsCardPlayer.size() - 1; i++) {
            for (int j = i + 1; j < dsCardPlayer.size(); j++) {
                if (dsCardPlayer.get(j).isLower(dsCardPlayer.get(i))) {
                    QuanBai temp = dsCardPlayer.get(i);
                    dsCardPlayer.set(i, dsCardPlayer.get(j));
                    dsCardPlayer.set(j, temp);
                }
            }
        }
    }

    public void baiNguoiChoi(int number, int type, int player) {
        int vitri = Math.abs(PlayerID - player);
        if (vitri == 1) {
            if (PlayerID > player) {
                vitri = 3;
            }
        }
        if (PlayerID == 3) {
            vitri = player + 1;
        }
        int x = 0, y = 0;
        QuanBai bai = new QuanBai(number, type, player);
        dsBaiDanh.add(bai);
        switch (vitri) {
            case 1:
                x = pnl.getWidth() / 3 + 25;
                y = pnl.getHeight() / 2 - bai.getHeight() / 2;
                removeCardLeft();
                System.out.println("\nplayer: " + player + " = left YouID: " + PlayerID);
                break;
            case 2:
                x = pnl.getWidth() / 2 - bai.getWidth() / 2;
                y = pnl.getHeight() / 3;
                removeCardTop();
                System.out.println("\nplayer: " + player + " = top YouID: " + PlayerID);
                break;
            case 3:
                x = pnl.getWidth() - pnl.getWidth() / 2;
                y = pnl.getHeight() / 2 - bai.getHeight() / 2;
                removeCardRight();
                System.out.println("\nplayer: " + player + " = right YouID: " + PlayerID);
                break;
        }
        bai.setLocation(x, y);
        pnl.add(bai, 0);
        pnl.updateUI();
        ktraKetQua();

    }

    public void showcard() {
        lblThongBao.setText("");
        btnDoi.setVisible(true);
        doiBai = true;
        //xoa bài cũ
        for (QuanBai card : dsCardLeft) {
            pnl.remove(card);
        }
        for (QuanBai card : dsCardTop) {
            pnl.remove(card);
        }
        for (QuanBai card : dsCardRight) {
            pnl.remove(card);
        }
        for (QuanBai card : dsCardPlayer) {
            pnl.remove(card);
        }
        showQuanBaiLeft();
        showQuanBaiTop();
        showQuanBaiRight();
        showQuanBaiPlayer();
        pnl.updateUI();
    }

    public void addButton_Label() {
        //Add lblThongBao
        lblThongBao = new JLabel("", JLabel.CENTER);
        lblThongBao.setSize(200, 21);
        lblThongBao.setForeground(Color.red);
        lblThongBao.setFont(new Font("tahoma", Font.BOLD, 12));
        lblThongBao.setLocation(pnl.getWidth() / 2 - lblThongBao.getWidth() / 2, pnl.getHeight() - 170);
        pnl.add(lblThongBao);
        //Add btnDoi
        btnDoi = new JButton("Pass");
        btnDoi.setSize(100, 25);
        int x = pnl.getWidth() / 2 - btnDoi.getWidth() / 2;
        int y = pnl.getHeight() - 200;
        btnDoi.setLocation(x, y);
        btnDoi.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                bntDoiBaiactionPerformed(e);
            }
        });
        pnl.add(btnDoi);
        //Addd lblLeft
        lblLeft = new JLabel(nameLeft, JLabel.CENTER);
        lblLeft.setSize(200, 21);
        lblLeft.setLocation(61 - lblLeft.getWidth() / 2, pnl.getHeight() / 2);
        lblLeft.setText("Player 1");
        pnl.add(lblLeft);
        //Add lblTop
        lblTop = new JLabel(nameTop, JLabel.CENTER);
        lblTop.setLocation(pnl.getWidth() / 2 - 200 / 2, 0);
        lblTop.setSize(200, 21);
        lblTop.setText("Player 2");
        pnl.add(lblTop);
        //Add lblRight
        lblRight = new JLabel(nameRight, JLabel.CENTER);
        lblRight.setSize(200, 21);
        lblRight.setLocation((pnl.getWidth()) - 61 - lblRight.getWidth() / 2, y + 71);
        lblRight.setText("Player 3");
        pnl.add(lblRight);

    }

    public void bntDoiBaiactionPerformed(ActionEvent evt) {
        lblThongBao.setText("");
        if (demBaiChon() < 3) {
            lblThongBao.setText("Chon 3 la bai.");
            return;
        }
        String msg = "12 " + PlayerID;
        Vector<QuanBai> BaiXoa = new Vector<>();
        for (QuanBai b : dsCardPlayer) {
            if (b.isUse == true) {
                msg += " " + b.number + " " + b.type;
                b.isUse = false;
                Point p = b.getLocation();
                b.setLocation(p.x, p.y + 25);
                BaiXoa.add(b);
                pnl.remove(b);
                pnl.updateUI();
            }
        }
        //xoa bài
        for (QuanBai b : BaiXoa) {
            dsCardPlayer.remove(b);
        }
        threadMain.send(msg);
        btnDoi.setVisible(false);
        doiBai = false;
        lblThongBao.setText("Cho doi bai.");
        //Kiem tra vi tri 2 chuon
        System.out.println("Doi Bai: " + msg);
    }

    //Ham Kiem tra xem client co cam 2 chuon hay khong
    public int viTriHaiChuon() {
        int vt = -1;
        for (int i = 0; i < dsCardPlayer.size(); i++) {
            if (dsCardPlayer.get(i).type == 1
                    && dsCardPlayer.get(i).number == 0) {
                vt = i;
                toiLuotDi();
                return i;
            }
        }
        return vt;
    }

    public void chonBaimousePressed(MouseEvent evt) {
        QuanBai quanbai = (QuanBai) evt.getComponent();
        if (doiBai == true) {
            Point p = quanbai.getLocation();
            if (quanbai.isUse == false) {
                if (demBaiChon() < 3) {
                    quanbai.setLocation(p.x, p.y - 25);
                    quanbai.isUse = true;
                }
            } else {
                quanbai.setLocation(p.x, p.y + 25);
                quanbai.isUse = false;
            }
        } else if (luotDi == true) {
            if (ktraLuat(quanbai) == true) {
                quanbai.isUse = true;
                baiDanhRa = quanbai;
                dsBaiDanh.add(quanbai);
                String msg = "7";//Head
                msg += " " + PlayerID + " " + quanbai.number + " " + quanbai.type;
                System.out.print("\nDanh Ra : " + msg);
                threadMain.send(msg);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(CuaSoGame.class.getName()).log(Level.SEVERE, null, ex);
                }
                int x = pnl.getWidth() / 2 - quanbai.getWidth() / 2;
                int y = pnl.getHeight() - pnl.getHeight() / 2;
                quanbai.setLocation(x, y);
                pnl.add(quanbai, 0);
                pnl.updateUI();
                hetLuotDi();
                ktraKetQua();
            } else {
                lblThongBao.setText("Khong dung duoc la bai nay.");
            }
        }

    }

    public boolean ktraLuat(QuanBai card) {
        lblThongBao.setText("");
        //Co bai thu 1 trong 4 con
        if (dsBaiDanh.size() <= 0) {
            if (card.number == 0 && card.type == 1) {
                return true;
            }
            for (QuanBai b : dsCardPlayer) {
                if (b.isUse == false && b.number == 0 && b.type == 1)//2 chuồn
                {
                    return false;
                }
            }
        } else {
            QuanBai cardDau = dsBaiDanh.get(0);
            //Nếu cùng chất (dạng) với lá bài đầu
            if (cardDau.type == card.type) {
                return true;
            }
            //Duyệt dsCardPlayer tìm con cùng chất
            for (QuanBai c : dsCardPlayer) {
                if (c.isUse == false && cardDau.type == c.type) {//Có con cùng chất phải đánh con cùng chất
                    return false;
                }
            }
        }
        //Không tìm thấy con nào cũng chất        
        return true;
    }

    public void ktraKetQua() {
        if (dsBaiDanh.size() >= 4) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                Logger.getLogger(CuaSoGame.class.getName()).log(Level.SEVERE, null, ex);
            }
            QuanBai cardDau = dsBaiDanh.get(0);
            if (cardDau.type == baiDanhRa.type) {
                int flag = 1;//Lớn nhất
                for (QuanBai card : dsBaiDanh) {
                    //Neu cung chat va nho nhat
                    if (card.type == baiDanhRa.type && baiDanhRa.number < card.number) {
                        flag = 0;//Khong lon nhat
                        break;
                    }
                }
                //Tinh diem
                if (flag == 1) {//Lớn nhất
                    int diemSo = 0;
                    for (QuanBai card : dsBaiDanh) {
                        if (card.type == 3) {//Bài chất cơ
                            diemSo++;
                        } else if (card.number == 10 && card.type == 0) {//Con Q bích
                            diemSo += 13;
                        }
                    }
                    //Send điểm
                    String msg = "2 " + PlayerID + " " + diemSo;
                    threadMain.send(msg);
                }
            }
            for (QuanBai card : dsBaiDanh) {
                pnl.remove(card);
            }
            dsBaiDanh.clear();
            pnl.updateUI();

        }
    }

    public int demBaiChon() {
        int dem = 0;
        for (QuanBai b : dsCardPlayer) {
            if (b.isUse == true) {
                dem++;
            }
        }
        return dem;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnl = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(700, 700));

        pnl.setBackground(new java.awt.Color(255, 255, 225));
        pnl.setMaximumSize(new java.awt.Dimension(700, 700));
        pnl.setMinimumSize(new java.awt.Dimension(700, 700));
        pnl.setPreferredSize(new java.awt.Dimension(0, 0));

        javax.swing.GroupLayout pnlLayout = new javax.swing.GroupLayout(pnl);
        pnl.setLayout(pnlLayout);
        pnlLayout.setHorizontalGroup(
            pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        pnlLayout.setVerticalGroup(
            pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnl, javax.swing.GroupLayout.PREFERRED_SIZE, 354, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnl, javax.swing.GroupLayout.PREFERRED_SIZE, 254, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CuaSoGame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CuaSoGame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CuaSoGame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CuaSoGame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CuaSoGame(null).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel pnl;
    // End of variables declaration//GEN-END:variables
}
